import time

from zpai_model import zpai

from uiautomation import WindowControl


# 绑定微信主窗口
wx = WindowControl(Name='微信', searchDepth=1)  # searchDepth=1参数指定在查找窗口时只搜索直接子级窗口，以提高查找效率
# 切换窗口
wx.ListControl()
wx.SwitchToThisWindow()  # ListControl()方法用于列出所有子级窗口，而SwitchToThisWindow()方法则将焦点切换到微信主窗口
# 寻找会话控件绑定
hw = wx.ListControl(Name='会话')

conversations = hw.GetChildren()  # GetChildren()方法，获取会话列表中的所有子控件。
jilu_num = 0


name = "悦悦已置顶"

for conversation in conversations:
    contact_name = conversation.Name
    if contact_name == name:  # 改成你想回复的联系人的名字
        conversation.Click(simulateMove=False)
        message_list = wx.ListControl(Name='消息').GetChildren()  # 获取消息列表中的所有子控件
        jilu_num = len(message_list)
        print(f"原本有{jilu_num}条消息")
        print("len(message_list)", len(message_list))
        print("new_msg_num", jilu_num)


role = zpai()

count = 1
# 死循环接收消息
while True:
    for conversation in conversations:
        contact_name = conversation.Name
        if contact_name == name:
            conversation.Click(simulateMove=False)

            # 增加延迟，确保消息发送的稳定性
            time.sleep(1)  # 延迟1秒，可以根据需要调整

            message_list = wx.ListControl(Name='消息').GetChildren()  # 获取消息列表中的所有子控件

            new_msg_num = len(message_list) - jilu_num
            if message_list:
                print("message_list", message_list[-1].Name)
            print("new_msg_num", new_msg_num)

            # 增加延迟，确保消息发送的稳定性
            time.sleep(1)  # 延迟1秒，可以根据需要调整

            #开场白
            if count == 1:
                ai_talk = "hello！我是虚拟【刘同学】，你可以和我聊天，问啥都可以哦！但是一次只能发一条消息【偷笑】"
                wx.SendKeys(f'{ai_talk}', waitTime=0)
                wx.SendKeys('{Enter}',waitTime=0)
                count = 0
                new_msg_num = 0
                message_list = wx.ListControl(Name='消息').GetChildren()  # 获取消息列表中的所有子控件
                jilu_num = len(message_list)

            if new_msg_num > 0:
                question = message_list[-1].Name
                # answer = my_classmate_zpai.answer_classmate(question)
                answer = role.answer_classmate(question)
                print("answer",answer)

                wx.SendKeys(f'{answer}', waitTime=0)
                wx.SendKeys('{Enter}',waitTime=0)

                new_msg_num = 0
                message_list = wx.ListControl(Name='消息').GetChildren()  # 获取消息列表中的所有子控件
                jilu_num = len(message_list)